import Vue from "vue";
import VueRouter from "vue-router";
import { Message } from "element-ui";
import store from "@/store/index";
import { getUserPermissions, getLoginInfo } from "@/api";
import { formatPermissionList } from "@/utils/auth";
Vue.use(VueRouter);
// ！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
// 注意！！！！！
// 加路由之后一定要去oa那边添加权限（找谭洪贵），不然会被路由守卫拦截
// ！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！

const whiteList = ["/401", "/403", "/404", "/file", "/console"];
const defaultSettings = {
  title: "职途运营中台",
};

const routes = [
  {
    path: "/",
    name: "Home",
    redirect: "/userProcessDataManage",
  },
  {
    path: "/userProcessDataManage",
    name: "UserProcessDataManage",
    component: () => import("../views/userProcessDataManage/index.vue"),
    meta: {
      routeTree: [
        {
          name: "首页",
        },
      ],
    },
  },
  {
    path: "/dataDetail",
    name: "DataDetail",
    component: () => import("../views/dataDetail/index.vue"),
    meta: {
      routeTree: [
        {
          name: "学生服务管理",
        },
      ],
    },
  },
  {
    path: "/cardManage",
    name: "CardManage",
    component: () => import("../views/cardManage/index.vue"),
    meta: {
      routeTree: [
        {
          name: "职途卡管理",
        },
      ],
    },
    children: [
      {
        path: "recordList",
        name: "RecordList",
        component: () => import("../views/cardManage/recordList/index.vue"),
        meta: {
          routeTree: [
            {
              name: "卡申请记录",
            },
          ],
        },
      },
      {
        path: "projectManage",
        name: "ProjectManage",
        component: () => import("../views/cardManage/projectManage/index.vue"),
        meta: {
          routeTree: [
            {
              name: "项目管理",
            },
          ],
        },
      },
    ],
  },
  {
    path: "/consultantManage",
    name: "ConsultantManage",
    redirect: "/consultantManage/consultantApplyManage",
    component: () => import("../views/consultantManage/index.vue"),
    meta: {
      routeTree: [
        {
          name: "顾问管理",
        },
      ],
    },
    children: [
      {
        path: "consultantApplyManage",
        name: "consultantApplyManage",
        component: () =>
          import("../views/consultantManage/consultantApplyManage/index.vue"),
        meta: {
          routeTree: [
            {
              name: "顾问申请管理",
            },
          ],
        },
      },
      {
        path: "consultantPersonManage",
        name: "consultantPersonManage",
        component: () =>
          import("../views/consultantManage/consultantPersonManage/index.vue"),
        meta: {
          routeTree: [
            {
              name: "顾问人员管理",
            },
          ],
        },
      },
    ],
  },
  {
    path: "/performance",
    name: "Performance",
    redirect: "/performance/overview",
    component: () => import("../views/performance/index.vue"),
    meta: {
      routeTree: [
        {
          name: "顾问绩效管理",
        },
      ],
    },
    children: [
      {
        path: "overview",
        name: "Overview",
        component: () => import("../views/performance/overview/index.vue"),
        meta: {
          routeTree: [
            {
              name: "顾问绩效总览",
            },
          ],
        },
      },
      {
        path: "performanceList",
        name: "PerformanceList",
        component: () =>
          import("../views/performance/performanceList/index.vue"),
        meta: {
          routeTree: [
            {
              name: "顾问绩效列表",
            },
          ],
        },
      },
      {
        path: "personalOverview",
        name: "PersonalOverview",
        component: () =>
          import("../views/performance/personalOverview/index.vue"),
        meta: {
          routeTree: [
            {
              name: "个人绩效总览",
            },
          ],
        },
      },
      {
        path: "performanceDetail",
        name: "PerformanceDetail",
        redirect: "/performance/performanceDetail/userAssessment",
        component: () =>
          import("../views/performance/performanceDetail/index.vue"),
        meta: {
          routeTree: [
            {
              name: "顾问绩效详情",
            },
          ],
          isNotBreadcrumb: true,
        },
        children: [
          {
            path: "userAssessment",
            name: "UserAssessment",
            component: () =>
              import(
                "../views/performance/performanceDetail/UserAssessment.vue"
              ),
            meta: {
              routeTree: [
                {
                  name: "用户评价",
                },
              ],
              isNotBreadcrumb: true,
            },
          },
          {
            path: "parseReportNum",
            name: "ParseReportNum",
            component: () =>
              import(
                "../views/performance/performanceDetail/ParseReportNum.vue"
              ),
            meta: {
              routeTree: [
                {
                  name: "用户报告数",
                },
              ],
              isNotBreadcrumb: true,
            },
          },
          {
            path: "userCaseNum",
            name: "UserCaseNum",
            component: () =>
              import("../views/performance/performanceDetail/UserCaseNum.vue"),
            meta: {
              routeTree: [
                {
                  name: "用户案例数",
                },
              ],
              isNotBreadcrumb: true,
            },
          },
          {
            path: "serviceUserNum",
            name: "ServiceUserNum",
            component: () =>
              import(
                "../views/performance/performanceDetail/ServiceUserNum.vue"
              ),
            meta: {
              routeTree: [
                {
                  name: "服务用户数",
                },
              ],
              isNotBreadcrumb: true,
            },
          },
          {
            path: "bindsUserNum",
            name: "BindsUserNum",
            component: () =>
              import(
                "../views/performance/performanceDetail/BindsUserNum.vue"
              ),
            meta: {
              routeTree: [
                {
                  name: "绑定用户数",
                },
              ],
              isNotBreadcrumb: true,
            },
          },
          {
            path: "timelyRate",
            name: "TimelyRate",
            component: () =>
              import("../views/performance/performanceDetail/TimelyRate.vue"),
            meta: {
              routeTree: [
                {
                  name: "回复及时率",
                },
              ],
              isNotBreadcrumb: true,
            },
          },
        ],
      },
      {
        path: "egg",
        name: "Egg",
        component: () => import("../views/performance/egg/index.vue"),
        meta: {
          routeTree: [
            {
              name: "彩蛋测试",
            },
          ],
        },
      },
    ],
  },
  {
    path: "/schedule",
    name: "Schedule",
    redirect: "/schedule/personSchedule",
    component: () => import("../views/schedule/index.vue"),
    meta: {
      routeTree: [
        {
          name: "排班",
        },
      ],
    },
    children: [
      {
        path: "personSchedule",
        name: "PersonSchedule",
        component: () => import("../views/schedule/personSchedule/index.vue"),
        meta: {
          routeTree: [
            {
              name: "个人排班",
            },
          ],
        },
      },
      {
        path: "allSchedule",
        name: "AllSchedule",
        component: () => import("../views/schedule/allSchedule/index.vue"),
        meta: {
          routeTree: [
            {
              name: "所有排班",
            },
          ],
        },
      },
    ],
  },
  {
    path: "/serviceTools",
    name: "ServiceTools",
    redirect: "/serviceTools/servicePage",
    component: () => import("../views/schedule/index.vue"),
    meta: {
      routeTree: [
        {
          name: "服务营销工具",
        },
      ],
    },
    children: [
      {
        path: "servicePage",
        name: "ServicePage",
        component: () => import("../views/serviceTools/servicePage/index.vue"),
        meta: {
          routeTree: [
            {
              name: "服务营销页",
            },
          ],
        },
      },
    ],
  },
  {
    path: "/orderManagement",
    name: "orderManagement",
    component: () => import("../views/orderManagement/index.vue"),
    meta: {
      routeTree: [
        {
          name: "订单管理",
        },
      ],
    },
  },
  {
    path: "/serviceTools",
    name: "ServiceTools",
    redirect: "/serviceTools/index",
    component: () => import("../views/serviceTools/index.vue"),
    meta: {
      routeTree: [
        {
          name: "服务营销工具",
        },
      ],
    },
    children: [
      {
        path: "dataOverview",
        name: "DataOverview",
        component: () => import("../views/serviceTools/dataOverview/index.vue"),
        meta: {
          routeTree: [
            {
              name: "推广数据总览",
            },
          ],
        },
      },
      {
        path: "behaviouralAnalysis",
        name: "BehaviouralAnalysis",
        component: () =>
          import("../views/serviceTools/behaviouralAnalysis/index.vue"),
        meta: {
          routeTree: [
            {
              name: "行为分析",
            },
          ],
        },
      },
      // {
      //   path: "analyzeData",
      //   name: "AnalyzeData",
      //   component: () => import("../views/serviceTools/analyzeData/index.vue"),
      //   meta: {
      //     routeTree: [
      //       {
      //         name: "行为分析数据",
      //       },
      //     ],
      //   },
      // },
    ],
  },
  {
    path: "/keyManage",
    name: "KeyManage",
    redirect: "/keyManage/orderDetail",
    component: () => import("../views/keyManage/index.vue"),
    meta: {
      routeTree: [
        {
          name: "兑换码管理",
        },
      ],
    },
    children: [
      {
        path: "orderDetail",
        name: "OrderDetail",
        component: () => import("../views/keyManage/orderDetail.vue"),
        meta: {
          routeTree: [
            {
              name: "订单详情",
            },
          ],
        },
      },
      {
        path: "key",
        name: "Key",
        component: () => import("../views/keyManage/key.vue"),
        meta: {
          routeTree: [
            {
              name: "兑换码",
            },
          ],
        },
      },
    ],
  },
  {
    path: "/systemSetting",
    name: "SystemSetting",
    redirect: "/systemSetting/publishNotice",
    component: () => import("../views/schedule/index.vue"),
    meta: {
      routeTree: [
        {
          name: "系统功能",
        },
      ],
    },
    children: [
      {
        path: "publishNotice",
        name: "PublishNotice",
        component: () =>
          import("../views/systemSetting/publishNotice/index.vue"),
        meta: {
          routeTree: [
            {
              name: "发布公告",
            },
          ],
        },
      },
    ],
  },
];

const router = new VueRouter({
  routes,
});

if (process.env.NODE_ENV === "production") {
  router.beforeEach((to, from, next) => {
    // 获取路由中的AppKey
    const AppKey = to.query.AppKey;
    if (AppKey) {
      sessionStorage.setItem("AppKey", AppKey);
      store.commit("SET_APP_KEY", AppKey);
    }
    const cInfo = sessionStorage.getItem("userInfo");
    const sid = to.query.sid;
    const route = decodeURIComponent(to.query.route || "");
    if (!!sid) {
      // 有sid,登录获取用户信息
      getLoginInfo({
        sid: sid,
      })
        .then((res) => {
          if (res.code == 200 || res.status == "OK") {
            sessionStorage.setItem("userInfo", JSON.stringify(res.userinfo));
            // 获取职途运营中台的菜单列表
            getUserPermissions().then((result) => {
              const temp = result.data.find(
                (item) => item.url === "/careerPathManage"
              );
              if (temp) {
                sessionStorage.setItem(
                  "AllPermissionList",
                  JSON.stringify(temp.permissionChildList)
                );
                store.commit(
                  "SET_ALL_PERMISSION_LIST",
                  formatPermissionList(temp.permissionChildList)
                );
                // routerPermissionControl(to, from, next);
                next(route || to.path);
              }
            });
          } else {
            Message.error("登录失败！请重新登录！");
            next(false);
          }
        })
        .catch((err) => {
          Message.error("登录失败！请重新登录！");
          next(false);
        });
    } else if (!cInfo) {
      // 没有登录信息
      Message.error("登录已失效，请重新登录！");
      next(false);
    } else {
      if ("/401" != to.path && !sessionStorage.getItem("AllPermissionList")) {
        // 获取职途运营中台的菜单列表
        getUserPermissions().then((result) => {
          const temp = result.data.find(
            (item) => item.url === "/careerPathManage"
          );
          if (temp) {
            sessionStorage.setItem(
              "AllPermissionList",
              JSON.stringify(temp.permissionChildList)
            );
            store.commit(
              "SET_ALL_PERMISSION_LIST",
              formatPermissionList(temp.permissionChildList)
            );
            routerPermissionControl(to, from, next);
          }
        });
      } else {
        const AllPermissionList = JSON.parse(
          sessionStorage.getItem("AllPermissionList")
        );
        store.commit(
          "SET_ALL_PERMISSION_LIST",
          formatPermissionList(AllPermissionList)
        );
        document.title = to.meta.title
          ? `${to.meta.title} · ${defaultSettings.title}`
          : defaultSettings.title;
        routerPermissionControl(to, from, next);
      }
    }
  });
} else {
  // 本地开发
  router.beforeEach((to, from, next) => {
    document.title = to.meta.title || defaultSettings.title;
    // 获取路由中的AppKey
    const AppKey = to.query.AppKey;
    if (AppKey) {
      sessionStorage.setItem("AppKey", AppKey);
      store.commit("SET_APP_KEY", AppKey);
    }
    if ("/401" != to.path && !sessionStorage.getItem("AllPermissionList")) {
      // 获取职途运营中台的菜单列表
      getUserPermissions().then((result) => {
        const temp = result.data.find(
          (item) => item.url === "/careerPathManage"
        );
        if (temp) {
          sessionStorage.setItem(
            "AllPermissionList",
            JSON.stringify(temp.permissionChildList)
          );
          store.commit(
            "SET_ALL_PERMISSION_LIST",
            formatPermissionList(temp.permissionChildList)
          );
          routerPermissionControl(to, from, next);
        }
      });
    } else {
      const AllPermissionList = JSON.parse(
        sessionStorage.getItem("AllPermissionList")
      );
      store.commit(
        "SET_ALL_PERMISSION_LIST",
        formatPermissionList(AllPermissionList)
      );
      document.title = to.meta.title
        ? `${to.meta.title} · ${defaultSettings.title}`
        : defaultSettings.title;
      routerPermissionControl(to, from, next);
    }
  });
}

function routerPermissionControl(to, from, next) {
  let list = JSON.parse(sessionStorage.getItem("AllPermissionList"));
  let urlList = [];
  function flatUrl(list) {
    list.map((item) => {
      if (Array.isArray(item.permissionChildList)) {
        flatUrl(item.permissionChildList);
      }
      if (item.type === 1) {
        urlList.push(item.url);
      }
    });
  }

  if (whiteList.includes(to.path)) {
    next();
  } else {
    flatUrl(list);
    if (urlList.includes(to.path)) {
      next();
    } else {
      next("/403");
    }
  }
}

export default router;
